<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\FrontendUser;
use App\Services\SettingService;
use Vinlon\Laravel\LayAdmin\Exceptions\AdminException;

class OpsController extends Controller
{
    /** 查询配置 */
    public function getSettings()
    {
        return opt()->batchGet([
            SettingService::OPT_TEST_MOBILES,
        ]);
    }

    /** 保存配置 */
    public function saveSettings()
    {
        request()->validate([
            'test_mobiles' => 'required',
        ]);

        // 检查手机号
        $mobiles = array_filter(explode(',', request()->test_mobiles));
        $existMobiles = FrontendUser::query()
            ->select(['mobile'])
            ->whereIn('mobile', $mobiles)
            ->distinct()
            ->get()->map(function (FrontendUser $user) {
                return $user->mobile;
            })->toArray();
        foreach ($mobiles as $mobile) {
            if (!in_array($mobile, $existMobiles)) {
                throw new AdminException('未找到手机号【' . $mobile . '】对应的用户');
            }
        }

        opt()->batchSet([
            SettingService::OPT_TEST_MOBILES => implode(',', $existMobiles),
        ]);
    }
}
